#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

void error_handling(char *message);

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <port>\n", argv[0]);
        exit(1);
    }

    int serv_sock, clnt_sock;
    struct sockaddr_in serv_addr, clnt_addr;
    socklen_t clnt_addr_size;

    // 创建套接字
    serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    if (serv_sock == -1)
        error_handling("socket() error");

    // 设置服务器信息
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(atoi(argv[1]));

    // 绑定套接字
    if (bind(serv_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
        error_handling("bind() error");

    // 监听套接字
    if (listen(serv_sock, 5) == -1)
        error_handling("listen() error");

    // 接受客户端连接
    clnt_addr_size = sizeof(clnt_addr);
    clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size);
    if (clnt_sock == -1)
        error_handling("accept() error");

    // 接收客户端认证信息
    char auth_msg[BUFFER_SIZE];
    read(clnt_sock, auth_msg, sizeof(auth_msg));

    // 在实际应用中进行用户认证，这里简单地回复认证成功
    char auth_result[] = "Authentication successful";
    write(clnt_sock, auth_result, sizeof(auth_result));

    printf("New client connected: %s\n", inet_ntoa(clnt_addr.sin_addr));

    // 聊天循环
    while (1) {
        char message[BUFFER_SIZE];

        // 接收客户端消息
        read(clnt_sock, message, sizeof(message));
        printf("Client: %s", message);

        // 发送回复消息
        printf("You: ");
        fgets(message, sizeof(message), stdin);
        write(clnt_sock, message, strlen(message));
    }

    // 关闭套接字
    close(clnt_sock);
    close(serv_sock);

    return 0;
}

void error_handling(char *message) {
    perror(message);
    exit(1);
}
